//
//  LYPublicMethod.m
//  artist
//
//  Created by laotang on 16/4/4.
//  Copyright © 2016年 viviyoo. All rights reserved.
//

#import "LYPublicMethod.h"
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "LYUrlManager.h"
#import <CoreTelephony/CTCarrier.h>
#import <AVFoundation/AVFoundation.h>
inline NSString *LYNoNullString(NSString *string)
{
    return (string ? string : @"");
}
inline NSString *LYURLString(NSString *urlString){
    
    return [NSString stringWithFormat:@"%@/%@", [LYUrlManager serverUrl], urlString];
}
inline UIColor *LYColorWithHexAndAlpha(long hexColor, float opacity)
{
    float red = ((float)((hexColor & 0xFF0000) >> 16))/255.0;
    float green = ((float)((hexColor & 0xFF00) >> 8))/255.0;
    float blue = ((float)(hexColor & 0xFF))/255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:opacity];
}

inline UIColor *LYColorWithHex(long hexColor)
{
    return LYColorWithHexAndAlpha(hexColor, 1.f);
}

IMP LSYSwizzleInstanceSelector(Class aClass, SEL original, IMP replacement)
{
    IMP imp = NULL;
    Method method = class_getInstanceMethod(aClass, original);
    if (method) {
        const char *type = method_getTypeEncoding(method);
        imp = class_replaceMethod(aClass, original, replacement, type);
        if (!imp) {
            imp = method_getImplementation(method);
        }
    }
    return imp;
}

IMP LSYSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation)
{
    // Get the original implementation we are replacing
    Class metaClass = objc_getMetaClass(class_getName(clazz));
    Method method = class_getClassMethod(metaClass, selector);
    IMP origImp = method_getImplementation(method);
    if (!origImp) {
        return NULL;
    }
    
    class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method));
    return origImp;
}
@implementation LYPublicMethod

+ (void)swizzleClassMethod:(Class)aClass swizzleSelector:(SEL)originSelector withSelector:(SEL)swizzleSelector
{
    Method otherMehtod = class_getClassMethod(aClass, swizzleSelector);
    Method originMehtod = class_getClassMethod(aClass, originSelector);
    method_exchangeImplementations(otherMehtod, originMehtod);
}

+ (void)swizzleInstanceMethod:(Class)aClass swizzleSelector:(SEL)originSelector withSelector:(SEL)swizzleSelector
{
    Method ori_Method =  class_getInstanceMethod(aClass, originSelector);
    Method my_Method = class_getInstanceMethod(aClass, swizzleSelector);
    method_exchangeImplementations(ori_Method, my_Method);
}




+ (BOOL)isPad
{
    static BOOL isPad;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        isPad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
    });
    return isPad;
}

+ (BOOL)iPhone6Puls
{
    static BOOL is6Puls;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        is6Puls = LYScreenWidth == 414;
    });
    return is6Puls;
}



+ (NSString *)platform
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    return platform;
}

+ (NSString *)currentOSVersion
{
    return [NSString stringWithString:[[UIDevice currentDevice] systemVersion]];
}

+ (NSString *)getShortVersionString
{
    static NSString *versionStr;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        versionStr = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
    });
    return versionStr;
}

+ (NSString *)getBuildVersionString
{
    static NSString *versionStr;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        versionStr = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    });
    return versionStr;
}

+ (NSString *)getBuildVersionDebugContainTestString
{
    static NSString *versionStr;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        versionStr = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        NSString *buildStr = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
#ifdef TT_USE_DEBUG_SERVER
        versionStr = [buildStr stringByAppendingString:@"(Test)"];
#else
        versionStr = buildStr;
#endif
    });
    return versionStr;
}

+ (NSString *)_platformString
{
    NSString *platform = [LYPublicMethod platform];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5C";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5S";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5S";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini (GSM)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (GSM)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (CDMA)";
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad 4 (GSM)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad 4 (CDMA)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini2 (WiFi)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini2 (GSM)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini2 (GSM+CDMA)";
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    else return                                         @"未能检测";
    return platform;
}

+ (LYArtistNetworkType)getNetworkTypeFromStatusBar
{
    //    CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
    //    NSString *curRATString = telephonyInfo.currentRadioAccessTechnology;
    //    __block LYArtistNetworkType nettype = LYArtistNetworkTypeNONE;
    //
    //    if(curRATString) {
    //        if ([curRATString isEqualToString:CTRadioAccessTechnologyLTE]) {
    //            nettype = LYArtistNetworkType4G;
    //        } else if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS]) {
    //            nettype = LYArtistNetworkType2G;
    //        } else {
    //            nettype =  LYArtistNetworkType3G;
    //        }
    //    }
    
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {
            dataNetworkItemView = subview;
            break;
        }
    }
    LYArtistNetworkType nettype = LYArtistNetworkTypeNONE;
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    nettype = [num intValue];
    
    return nettype;
}

+ (NSString *)getNetworkTypeStrFromStatusBar
{
    LYArtistNetworkType nettype = [self getNetworkTypeFromStatusBar];
    NSString *typeStr = @"NONE";
    
    switch (nettype) {
        case LYArtistNetworkTypeNONE: {
            break;
        }
        case LYArtistNetworkType2G: {
            typeStr = @"2G";
            break;
        }
        case LYArtistNetworkType3G: {
            typeStr = @"3G";
            break;
        }
        case LYArtistNetworkType4G: {
            typeStr = @"4G";
            break;
        }
        case LYArtistNetworkTypeWIFI: {
            typeStr = @"WIFI";
            break;
        }
        default: {
            break;
        }
    }
    
    return typeStr;
}

+ (NSString *)getSubscriberCellularProviderStr
{
    CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
    return telephonyInfo.subscriberCellularProvider.carrierName;
}


+ (BOOL)checkPhotoLibraryAuthorizationStatus
{
    //    if ([ALAssetsLibrary respondsToSelector:@selector(authorizationStatus)])
    {
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        if (ALAuthorizationStatusDenied == authStatus ||
            ALAuthorizationStatusRestricted == authStatus) {
            [self showSettingAlertStr:@"请在iPhone的“设置->隐私->照片”中打开本应用的访问权限"];
            return NO;
        }
    }
    return YES;
}

+ (BOOL)checkCameraAuthorizationStatus
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"该设备不支持拍照" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil] show];
        return NO;
    }
    
    if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)]) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (AVAuthorizationStatusDenied == authStatus ||
            AVAuthorizationStatusRestricted == authStatus) {
            [self showSettingAlertStr:@"请在iPhone的“设置->隐私->相机”中打开本应用的访问权限"];
            return NO;
        }
    }
    
    return YES;
}

+ (void)showSettingAlertStr:(NSString *)tipStr{

    [[[UIAlertView alloc] initWithTitle:@"提示" message:tipStr delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil] show];
}
+ (NSString *)getReduceStringByContent:(NSString *)content
{
    if (!content) {
        return nil;
    }
    NSString *resultString = [NSString stringWithString:content];
    NSArray *emojiStrArray = @[@"[微笑]",
                               @"[撇嘴]",
                               @"[色]",
                               @"[发呆]",
                               @"[得意]",
                               @"[流泪]",
                               @"[害羞]",
                               @"[闭嘴]",
                               @"[睡]",
                               @"[大哭]",
                               @"[尴尬]",
                               @"[发怒]",
                               @"[调皮]",
                               @"[呲牙]",
                               @"[惊讶]",
                               @"[难过]",
                               @"[酷]",
                               @"[冷汗]",
                               @"[抓狂]",
                               @"[吐]",
                               @"[偷笑]",
                               @"[可爱]",
                               @"[白眼]",
                               @"[饥饿]",
                               @"[困]",
                               @"[惊恐]",
                               @"[憨笑]",
                               @"[拍砖]",
                               @"[嘘]",
                               @"[晕]",
                               @"[囧]",
                               @"[衰]",
                               @"[再见]",
                               @"[恶魔怒]",
                               @"[恶魔喜]",
                               @"[柴犬笑]",
                               @"[柴犬色]",
                               @"[坏笑]",
                               @"[抠鼻]",
                               @"[委屈]",
                               @"[亲亲]",
                               @"[无语]",
                               @"[贱笑]",
                               @"[鄙视]",
                               @"[可怜]",
                               @"[惊吓]",
                               @"[猪]",
                               @"[心碎]",
                               @"[爱心]",
                               @"[礼物]",
                               @"[骨头]",
                               @"[刀]",
                               @"[好]",
                               @"[顶]",
                               @"[踩]",
                               @"[玫瑰]",
                               @"[嘴唇]",
                               @"[粪]",
                               @"[抱抱]",
                               @"[茶]",
                               @"[月亮]",
                               @"[太阳]",
                               @"[闪电]",
                               @"[饮品]",
                               @"[蛋糕]",
                               @"[棒棒糖]"];
    for (NSString *str in emojiStrArray) {
        if ([resultString hasSuffix:str] && str.length && resultString.length) {
            //后缀有包括
            NSRange range = NSMakeRange(resultString.length - str.length, str.length);
            resultString = [resultString substringToIndex:range.location];
            break;
        }
    }
    return resultString;
}


+ (void)loginRongLianYunWithLoginInfo:(LYUserInfoModel *)loginUserInfo{
    
    
    ECLoginInfo * loginInfo = [[ECLoginInfo alloc] init];
    [DemoGlobalClass sharedInstance].userName = loginUserInfo.chat_info.user_id;
    loginInfo.username = loginUserInfo.chat_info.voip_account;
    loginInfo.userPassword = loginUserInfo.chat_info.voip_pwd;
    loginInfo.appToken = [DemoGlobalClass sharedInstance].appToken;
    loginInfo.appKey = [DemoGlobalClass sharedInstance].appKey;
    loginInfo.authType = LoginAuthType_PasswordAuth;
    loginInfo.mode = LoginMode_InputPassword;
    [[ECDevice sharedInstance] login:loginInfo completion:^(ECError *error){
        //打开本地数据库
        
        //        NSString *userName = loginUserInfo.username;
        
        NSLog(@"%@", loginUserInfo.chat_info.user_id);
        [[DeviceDBHelper sharedInstance] openDataBasePath:[DemoGlobalClass sharedInstance].userName];
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onConnected object:error];
        if (error.errorCode == ECErrorType_NoError) {
            LYLog(@"登陆成功");
        }else{
            [self loginRongLianYunWithLoginInfo:loginUserInfo]; // 递归登录， 直到登录成功
        }
    }];
}

@end
